<?php

/**
 * 首页控制器
 *
 * @author susy<liangling@ilongyuan.com.cn>
 */
/***************change log *******************
+----首页加比赛， 逛一逛 susy.laing<liangling@ilongyuan.com.cn> at 2015/7/6
*********************************************/


namespace Home\Controller;

use Api\Event\CacheEvent;

class IndexController extends HomeController {

	/**
	 * 基础参数的初始化
	 */
	protected function _initialize() {
		parent::_initialize();
		$this->isIndex = 1;
	}
 
 	public function test()
 	{
 		$redirect = U('Home/Sso/code', ['channel'=>'weixin', 'redirect_url' => base64_encode('http://test.66play.com')], false, true);
 		$redirect = urlencode($redirect);
 		header("location: https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx8c0229cea7f27b8a&redirect_uri={$redirect}&response_type=code&scope=snsapi_login&state=#wechat_redirect");
 		// echo 'weixin share';
 	}

	public function index() {
        if (IS_MOBILE) {
            $this->redirect('/download/mobile');
            return;
        }
        setRedirect();
        $this->partners = $this->partner();
        $this->adCode = ['webindextvbanner', 'webindexbanner'];

        $notice = event('News')->lists(['type' => 1], 1, 1);
        if (!empty($notice)) {
            $this->notice = $notice[0];
        }
		C('DEFAULT_THEME', 'v4');
        $this->display();
    }

    /**
     * 热门比赛
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function ajaxHotRace() {
        $cache_key = 'IMBA.CACHE.WEB.INDEX.RACES';
        $Redis = CacheEvent::instance(0);
        $data = $Redis->get($cache_key);
        unset($Redis);
        $data = json_decode($data, true);
        if (empty($data)) {
            $data = [];
            $eventObj = A('Api/RaceGroup', 'Event');
            $videoEvent = A('Api/Video', 'Event');
            $curDate = date('Y-m-d', time());
            $map = array(
                    'state'=>1,
                    'race_date'=>array('lt', $curDate)
                );
            $ids = $eventObj->lists($map, 'id', 4, 0, 'race_time desc');
            $fieldMap = array('id', 'title', 'subtitle', 'race_date', 'race_hour', 'score', 'team', 'game', 'match', 'list', 'cover');
            foreach ($ids as $key => $value) {
                $detail = $eventObj->info($value['id']);
                $detail['score'] = $detail['score']?array_map('intval', explode('-', $detail['score'])):array();
                $detail['game'] = $this->field_filter($detail['game'], array('id','name','logo'));
                $detail['match'] = $this->field_filter($detail['match'], array('id','title','cover'));
                $races = $videoEvent->lists(['group_id' => $detail['id'], 'type' => 1], 0, true);
                if (!empty($races) && is_array($races)) {
                    sort($races);
                    $races = array_slice($races, 0, 3);
                }
                $detail = $this->field_filter($detail, $fieldMap);
                $detail['races'] = $races;

                uri_format($detail['cover']);
                uri_format($detail['match']['cover']);
                uri_format($detail['match']['pc_cover']);
                $detail['cover'] = $detail['cover'] ?: ($detail['match']['cover']?:$detail['match']['pc_cover']);
                $data[] = $detail;
            }
            $Redis = CacheEvent::instance(0);
            $Redis->setEx($cache_key, 600, json_encode($data));
            unset($Redis);
        }
        $this->data = $data;
        C('DEFAULT_THEME', 'v4');
        $html = $this->fetch('race_template');
        $this->ajaxReturn(['state' => 0, 'html' => $html]);
    }

    /**
     * 精彩视频
     * @author liubo <liubo@ilongyuan.com.cn>
     * @return [type] [description]
     */
    public function ajaxHotVideo() {
        $cache_key = 'IMBA.CACHE.WEB.INDEX.VIDEOS';
        $Redis = CacheEvent::instance(0);
        $data = $Redis->get($cache_key);
        unset($Redis);
        $videos = json_decode($data, true);
        if (empty($videos)) {
            $topicId = 3;// 编辑选推
            $videos = event('Video')->getByTopicAndGame($topicId, [], 0, 8);

            $filterMap = array('id','title','thumb','pre_uri','uri','detail','user','statis','action','create_time','game_id','game','type','icons', 'tags', 'type', 'status');
            $videos = $this->lists_format($videos, $filterMap);
            $Redis = CacheEvent::instance(0);
            $Redis->setEx($cache_key, 600, json_encode($videos));
            unset($Redis);
        }

        $this->data = $videos;
        C('DEFAULT_THEME', 'v4');
        $html = $this->fetch('video_template');
        $this->ajaxReturn(['state' => 0, 'html' => $html]);
    }

    /**
     * 合作伙伴
     * @author liubo <liubo@ilongyuan.com.cn>
     * @return [type] [description]
     */
    private function partner() {
        $partners = service('Partner')->order('sort asc')->select();
        $data = [];
        foreach ($partners as $value) {
            uri_format($value['logo']);
            $data[] = $value;
        }
        return $data;
    }

	/**
	*网站入口页  ->  改为一个中转页   
	*登录用户转到个人中心页
	*非登录用户转到广场页
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function index_redirect(){
		if(UID)
			$this->redirect('Ucenter/index');
		else
			$this->redirect('Index/square');
	}

	/**
	 * 广场页
	 *@author susy.liang<liangling@ilongyuan.com.cn>
	 */
	public function square() {
		$this->redirect('Index/index');
		/*$vEvent = A('Api/Video', 'Event');
		$recommend =  $vEvent->getRecommend(C('VIDEO_INDEX_LIMIT'));

		$filterMap = array('id','title','thumb','pre_uri','uri','detail','user','statis','action');
		$recommend = $this->lists_format($recommend, $filterMap);*/
		// 修改为做推荐位的视频信息  2015-5-29 17:24:02 Legend.
		$recommend = A( 'Api/Recommend', 'Event' )->getLists();

		$gEvent  = A( 'Api/Game', 'Event' );
		$field   = 'id,name,cover,detail';
		$games   = $gEvent->lists( '', $field );

		$gameData = array();
		foreach ( $games as $key => &$game ) {
			uri_format( $game['cover'] );
			$gameData[] = $game;
		}

		$mEvent = A( 'Api/Match', 'Event' );
		$match = $mEvent->lists( 0, 0, false, 'id,title,cover' );
		foreach ( $match as $key => &$value ) {
			uri_format( $value['logo'] );
			uri_format( $value['cover'] );
		}

		$races = $mEvent->getDefRaces(3);

		$ad = A( 'Api/Ad', 'Event' )->lists( 'RP' );
		if('1' === cookie('noAd')){
			$ad = null;
		}

		$this->data = array(
			'videos' => $recommend,
			'games'  => $gameData,
			'match'  => $match,
			'races'  => $races,
			'ad'     => $ad,
			'nav'    => true
		);

		$this->display();
	}


	/**
	 * 获取首页下所有视频栏目，最热视频，最新视频
	 *
	 * @return html返回
	 *@author susy.liang<liangling@ilongyuan.com.cn>
	 */
	public function getCate() {
		$vEvent = A( 'Api/Video', 'Event' );

		$filterMap = array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'detail', 'user', 'statis', 'action', 'game', 'time' );

		$hotVideos = $vEvent->getHot( C( 'HOT_VIDEO_LIMIT' ) );
		$hotVideos = $this->lists_format( $hotVideos, $filterMap );

		$newsVideos = $vEvent->getNew( C( 'HOT_VIDEO_LIMIT' ) );
		$newsVideos = $this->lists_format( $newsVideos, $filterMap );

		$data['hot'] = $hotVideos;

		$data['new'] = $newsVideos;

		$tEvent = A( 'Api/Topic', 'Event' );

		$topics = $tEvent->getHomeTopics( false );
		$vEvent = A( 'Video', 'Event' );
		foreach ( $topics as $topic ) {
			$videos = $topic['videos'];
			if ( $videos ) {
				$videos = explode( ',', $videos );
			}
			$videos = $this->lists_format( $videos, $filterMap );

			$data['cate'][] = array(
				'id'=>$topic['id'],
				'title'=>$topic['title'],
				'lists'=>$videos,
			);
		}

		$this->data = $data;

		$strhtml = $this->fetch( 'Template:index' );

		$this->ajaxReturn( array( 'state'=>0, 'data'=>array( 'content'=>$strhtml ) ) );
	}

	/**
	*关于我们
	*@author zhaoweis
	*/
	public function aboutUs() {
		$agent = strtolower( $_SERVER['HTTP_USER_AGENT'] );
		if ( strpos( $agent, 'iphone' ) || strpos( $agent, 'ipad' ) ) {
			$type = 'ios';
		}else if ( strpos( $agent, 'android' ) ) {
				$type = 'android';
			}else {
			$type = 'ios_jailbreak';
		}

		$v = A( 'Api/AppVersion', 'Event' )->getLatest( $type );
		$this->version = $v['outer_version'];

		$this->display( 'aboutUs' );
	}

	/**
	*广告不要不要的
	*@author zhaowei
	*/
	public function noMoreAd() {
		//modify by susy.liang change the effective time to 3 hours
		//return cookie('noAd', true, 3 * 60 * 3600);
		return cookie('noAd', true, time()+3*3600);
		//end
	}

	/**
	*用户协议
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function agreement(){

		$this->display();
	}

	/**
	*逛一逛
	*随机取视频或比赛数据
	*@author susy.liang<liangling@ilongyuan.com.cn>
	*/
	public function stroll(){

		$vEvent = A('Api/Video', 'Event');
		$video_ids = $vEvent->randomLists();

		$fieldMap =  array( 'id', 'title', 'thumb', 'pre_uri', 'uri', 'time', 'detail', 
                    'create_time', 'game_id', 'game', 'uid', 'user', 'statis', 'tags', 
                    'action', 'icons', 'type'
                    );
		$lists = $this->lists_format($video_ids, $fieldMap);

	 	$this->data = $lists;

	 	$this->isIndex = 0;

	 	$this->display();
	}
}